import { ElMessage } from 'element-plus'

export interface TradeAccount {
    id: string
    site: string
    account: string
    accountNickname: string
    phone: string
    status: string
    balance?: number
    lastUsed?: string
}

export interface AccountConfig {
    order: number
    accountId: string
    accountNickname: string
    account: string
    phone: string
    times: number
    usedTimes?: number
    remainingTimes?: number
}

export interface AutoBidConfig {
    enabled: boolean
    accounts: AccountConfig[]
    createdAt?: string
    updatedAt?: string
}

export interface AutoBidStats {
    totalBids: number
    successfulBids: number
    failedBids: number
    totalAmount: number
    todayBids: number
    todayAmount: number
}

class AutoBidService {
    private baseUrl = '/api/auto-bid'

    /**
     * 获取交易账号列表
     */
    async getTradeAccounts(): Promise<TradeAccount[]> {
        try {
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 500))

            return [
                {
                    id: 'TA001',
                    site: 'yahoo_auction',
                    account: 'yahoo_user1',
                    accountNickname: '雅虎拍卖账号1',
                    phone: '13800138001',
                    status: '启用',
                    balance: 50000,
                    lastUsed: '2024-01-15 14:30:00'
                },
                {
                    id: 'TA002',
                    site: 'mercari',
                    account: 'mercari_user2',
                    accountNickname: '煤炉账号2',
                    phone: '13800138002',
                    status: '启用',
                    balance: 30000,
                    lastUsed: '2024-01-15 16:45:00'
                },
                {
                    id: 'TA003',
                    site: 'yahoo_flea',
                    account: 'yahoo_flea_user',
                    accountNickname: '雅虎闲置账号',
                    phone: '13800138003',
                    status: '启用',
                    balance: 25000,
                    lastUsed: '2024-01-15 12:15:00'
                },
                {
                    id: 'TA004',
                    site: 'rakuten',
                    account: 'rakuten_user1',
                    accountNickname: '乐天账号1',
                    phone: '13800138004',
                    status: '启用',
                    balance: 40000,
                    lastUsed: '2024-01-15 10:20:00'
                },
                {
                    id: 'TA005',
                    site: 'amazon',
                    account: 'amazon_user1',
                    accountNickname: '亚马逊账号1',
                    phone: '13800138005',
                    status: '启用',
                    balance: 60000,
                    lastUsed: '2024-01-15 18:30:00'
                }
            ]
        } catch (error) {
            console.error('获取交易账号失败:', error)
            ElMessage.error('获取交易账号失败')
            return []
        }
    }

    /**
     * 获取会员的自动出价配置
     */
    async getAutoBidConfig(memberId: string): Promise<AutoBidConfig | null> {
        try {
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 300))

            // 从localStorage获取配置（实际应该从API获取）
            const savedConfig = localStorage.getItem(`autoBidConfig_${memberId}`)
            if (savedConfig) {
                return JSON.parse(savedConfig)
            }

            return null
        } catch (error) {
            console.error('获取自动出价配置失败:', error)
            ElMessage.error('获取配置失败')
            return null
        }
    }

    /**
     * 保存自动出价配置
     */
    async saveAutoBidConfig(memberId: string, config: AutoBidConfig): Promise<boolean> {
        try {
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 800))

            // 保存到localStorage（实际应该保存到API）
            localStorage.setItem(`autoBidConfig_${memberId}`, JSON.stringify({
                ...config,
                updatedAt: new Date().toISOString()
            }))

            return true
        } catch (error) {
            console.error('保存自动出价配置失败:', error)
            ElMessage.error('保存配置失败')
            return false
        }
    }

    /**
     * 删除自动出价配置
     */
    async deleteAutoBidConfig(memberId: string): Promise<boolean> {
        try {
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 300))

            // 从localStorage删除配置（实际应该从API删除）
            localStorage.removeItem(`autoBidConfig_${memberId}`)

            return true
        } catch (error) {
            console.error('删除自动出价配置失败:', error)
            ElMessage.error('删除配置失败')
            return false
        }
    }

    /**
     * 获取自动出价统计信息
     */
    async getAutoBidStats(memberId: string): Promise<AutoBidStats | null> {
        try {
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 400))

            return {
                totalBids: 156,
                successfulBids: 142,
                failedBids: 14,
                totalAmount: 1250000,
                todayBids: 8,
                todayAmount: 45000
            }
        } catch (error) {
            console.error('获取统计信息失败:', error)
            return null
        }
    }

    /**
 * 测试自动出价配置
 */
    async testAutoBidConfig(memberId: string, config: AutoBidConfig): Promise<{
        success: boolean
        message: string
        details?: any
    }> {
        try {
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 2000))

            // 模拟测试结果
            const testResults = {
                success: Math.random() > 0.2, // 80%成功率
                message: Math.random() > 0.2 ? '测试成功，配置有效' : '测试失败，请检查配置',
                details: {
                    testedAccounts: config.accounts.length,
                    validAccounts: Math.floor(config.accounts.length * 0.8),
                    estimatedBidTime: 5 * config.accounts.length // 默认5秒间隔
                }
            }

            return testResults
        } catch (error) {
            console.error('测试配置失败:', error)
            return {
                success: false,
                message: '测试失败，请重试'
            }
        }
    }

    /**
     * 批量更新账号使用次数
     */
    async updateAccountUsage(memberId: string, accountUpdates: Array<{
        accountId: string
        usedTimes: number
    }>): Promise<boolean> {
        try {
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 500))

            // 更新localStorage中的配置
            const savedConfig = localStorage.getItem(`autoBidConfig_${memberId}`)
            if (savedConfig) {
                const config = JSON.parse(savedConfig)
                accountUpdates.forEach(update => {
                    const account = config.accounts.find((acc: AccountConfig) => acc.accountId === update.accountId)
                    if (account) {
                        account.usedTimes = (account.usedTimes || 0) + update.usedTimes
                        account.remainingTimes = account.times - account.usedTimes
                    }
                })
                localStorage.setItem(`autoBidConfig_${memberId}`, JSON.stringify(config))
            }

            return true
        } catch (error) {
            console.error('更新账号使用次数失败:', error)
            return false
        }
    }

    /**
 * 获取推荐配置
 */
    getRecommendedConfig(memberLevel: string): Partial<AutoBidConfig> {
        const recommendations: Record<string, Partial<AutoBidConfig>> = {
            'L1': {
                enabled: false
            },
            'L2': {
                enabled: false
            },
            'L3': {
                enabled: true
            },
            'L4': {
                enabled: true
            },
            'L5': {
                enabled: true
            },
            'L6': {
                enabled: true
            },
            'L7': {
                enabled: true
            }
        }

        return recommendations[memberLevel] || recommendations['L1']
    }

    /**
 * 验证配置有效性
 */
    validateConfig(config: AutoBidConfig): {
        valid: boolean
        errors: string[]
    } {
        const errors: string[] = []

        if (!config.enabled) {
            return { valid: true, errors: [] }
        }

        // 验证账号配置
        if (config.accounts.length === 0) {
            errors.push('至少需要配置一个交易账号')
        }

        for (const account of config.accounts) {
            if (!account.accountId) {
                errors.push('请选择交易账号')
            }
            if (account.times <= 0) {
                errors.push('使用次数必须大于0')
            }
        }

        return {
            valid: errors.length === 0,
            errors
        }
    }
}

export const autoBidService = new AutoBidService() 